package com.huajx.tb.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import java.io.*;

/**
 * 编码 天波 能龙协议处理
 * 
 * @author xhye
 *
 */
public class NengLongEncoder implements ProtocolEncoder {

	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		if (message == null) {
			return;
		}

		// 消息类型判断处理
		if (message instanceof String) {
			byte[] gbkMsg = convertEncoding_ByteArr(((String) message).getBytes(), "UTF-8", "GB2312");//gbk.getBytes("gb2312");

			out.write(IoBuffer.wrap(gbkMsg));
		} else if (message instanceof byte[]) {
			out.write(IoBuffer.wrap((byte[]) message));
		} else if(message instanceof StringBuilder) {
			out.write(IoBuffer.wrap(((StringBuilder)message).toString().getBytes()));
		} else if(message instanceof StringBuffer) {
			out.write(IoBuffer.wrap(((StringBuffer)message).toString().getBytes()));
		}
	}

	@Override
	public void dispose(IoSession session) throws Exception {

	}

	/**
	 * 中文编码转换
	 * @param src
	 * @param srcCharset
	 * @param destCharet
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public byte[]  convertEncoding_ByteArr(byte[] src,String srcCharset,String destCharet)
			throws UnsupportedEncodingException{
		String s = new String(src, srcCharset);
		return s.getBytes(destCharet);
	}
}
